import Vue from 'vue'
import Vuex from 'vuex'
import api from "@/api/api"
import MinCache from'@/common/util/MinCache.js'
import { ACCESS_TOKEN,TOKEN_TYPE,USER_NAME,USER_INFO,X_TENANT_ID } from "@/common/util/constants"

Vue.use(Vuex)


let lifeData = {}

// 尝试获取本地是否存在lifeData变量，第一次启动时不存在
try {
  lifeData = uni.getStorageSync('lifeData')
} catch(e) {
  
}

// 标记需要永久存储的变量，在每次启动时取出，在state中的变量名
let saveStateKeys = ['vuex_user']

// 保存变量到本地存储
const saveLifeData = function(key, value) {
  // 判断变量是否在存储数组中
  if (saveStateKeys.indexOf(key) != -1) {
    // 获取本地存储的lifeData对象，将变量添加到对象中
    let tmpLifeData = uni.getStorageSync('lifeData')
    // 第一次启动时不存在，则放一个空对象
    tmpLifeData = tmpLifeData ? tmpLifeData : {},
    tmpLifeData[key] = value
    // 将变量再次放回本地存储中
    uni.setStorageSync('lifeData', tmpLifeData)
  }
}


export default new Vuex.Store({
  state: {
    token: '',
	tokenType:'',
    userid:'',
    username: '',
    realname: '',
    welcome: '',
    avatar: '',
	my_custom_nav_bar_height:0,
	logoData:'',
	// 如果上面从本地获取的lifeData对象下有对应的属性，就赋值给state中对应的变量
	// 加上vuex_前缀，是防止变量名冲突，也让人一目了然
	vuex_user: lifeData.vuex_user ? lifeData.vuex_user : {name: '图鸟'},
	
	// 如果vuex_version无需保存到本地永久存储，无需lifeData.vuex_version方式
	// app版本
	vuex_version: "1.0.0",
	// 是否使用自定义导航栏
	vuex_custom_nav_bar: true,
	// 状态栏高度
	vuex_status_bar_height: 0,
	// 自定义导航栏的高度
	vuex_custom_bar_height: 0
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
	SET_TOKEN_TYPE:(state, tokenType)=>{
		state.tokenType = tokenType
	},
    SET_NAME: (state, { username, realname, welcome }) => {
      state.username = username
      state.realname = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
	SET_LOGO_DATA(state,payload){
		state.logoData = payload
	},
	$tStore(state, payload) {
	  // 判断是否多层调用，state中为对象存在的情况，例如user.info.score = 1
	  let nameArr = payload.name.split('.')
	  let saveKey = ''
	  let len = nameArr.length
	  if (len >= 2) {
	    let obj = state[nameArr[0]]
	    for (let i= 1; i < len - 1; i++) {
	      obj = obj[nameArr[i]]
	    }
	    obj[nameArr[len - 1]] = payload.value
	    saveKey = nameArr[0]
	  } else {
	    // 单层级变量
	    state[payload.name] = payload.value
	    saveKey = payload.name
	  }
	  
	  // 保存变量到本地中
	  saveLifeData(saveKey, state[saveKey])
	},
	set_navBarHeight(state,height){
		state.my_custom_nav_bar_height = height;
	},
	
  },
  actions: {
	  loginByManage({ commit }, loginUserInfo){
		  return new Promise((resolve, reject) => {
		   api.loginByAdmin(loginUserInfo).then(response => {
		      if(response.data.status ==200){ 
		        const result = response.data.data;
		        const userInfo = result.user_info;
		  			uni.setStorageSync(ACCESS_TOKEN,result.token);
		  			uni.setStorageSync(TOKEN_TYPE,result.token_type);
		  			uni.setStorageSync(USER_INFO,userInfo);
					commit('SET_TOKEN', result.token)
					commit('SET_TOKEN_TYPE',result.token_type);
					commit('SET_AVATAR', userInfo.avatar)
					commit('SET_NAME', { username: loginUserInfo.username,realname: loginUserInfo.realname})
					resolve(response)
		      }else{
		        resolve(response)
		      }
		    }).catch(error => {
		  			console.log("catch===>response",error)
		      reject(error)
		    })
		  })
	  },
    // 登录
    mLogin({ commit }, loginUserInfo) {
      return new Promise((resolve, reject) => {
       api.login(loginUserInfo).then(response => {
          if(response.data.status ==200){ 
            const result = response.data.data;
            const userInfo = result.user_info;
			uni.setStorageSync(ACCESS_TOKEN,result.token);
			uni.setStorageSync(TOKEN_TYPE,result.token_type);
			uni.setStorageSync(USER_INFO,userInfo);
            commit('SET_TOKEN', result.token)
			commit('SET_TOKEN_TYPE',result.token_type);
            commit('SET_AVATAR', userInfo.avatar)
            commit('SET_NAME', { username: loginUserInfo.username,realname: loginUserInfo.realname})
            resolve(response)
          }else{
            resolve(response)
          }
        }).catch(error => {
			console.log("catch===>response",error)
          reject(error)
        })
      })
    },
    //手机号登录
    PhoneLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        api.phoneNoLogin(userInfo).then(response => {
          if(response.data.code ==200){
            const result = response.data.result
            const userInfo = result.userInfo
			uni.setStorageSync(ACCESS_TOKEN,result.token);
			uni.setStorageSync(USER_INFO,userInfo);
            commit('SET_TOKEN', result.token)
            commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname})
            commit('SET_AVATAR', userInfo.avatar)
            resolve(response)
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 第三方登录
    ThirdLogin({ commit }, param) {
      return new Promise((resolve, reject) => {
        api.thirdLogin(param.token,param.thirdType,param.tenantId).then(response => {
          if(response.data.code =='200'){
            const result = response.data.result
            const userInfo = result.userInfo
            uni.setStorageSync(ACCESS_TOKEN,result.token);
            uni.setStorageSync(USER_INFO,userInfo);
            uni.setStorageSync(X_TENANT_ID,userInfo.loginTenantId);

            commit('SET_TOKEN', result.token)
            commit('SET_AVATAR', userInfo.avatar)
            commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname })
            commit('SET_ID', userInfo.id)
            commit('SET_INFO', userInfo)
            commit('SET_TENANTID', userInfo.loginTenantId)
            resolve(response)
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        let logoutToken = state.token;
        commit('SET_TOKEN', '')
        uni.removeStorageSync(ACCESS_TOKEN)
        api.logout(logoutToken).then(() => {
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    },

  },
  getters:{
    token: state => state.token,
	username: state => {state.userid=uni.getStorageSync(USER_INFO).username; return state.username},
	nickname: state => {state.userid=uni.getStorageSync(USER_INFO).realname; return state.user.realname},
	avatar: state => {state.userid=uni.getStorageSync(USER_INFO).avatar; return state.user.avatar},
	userid:state => {state.userid=uni.getStorageSync(USER_INFO).id; return state.userid},
	my_custom_navBarHeight:state=>state.my_custom_nav_bar_height,
  }
})
